# 输入一个矩阵，按照从外向里以顺时针的顺序依次打印出每一个数字。
# https://leetcode.cn/problems/shun-shi-zhen-da-yin-ju-zhen-lcof/
#
# 输入：matrix = [[1,2,3],[4,5,6],[7,8,9]]
# 输出：[1,2,3,6,9,8,7,4,5]


class Solution:
    def spiralOrder(self, matrix):
        if len(matrix) < 1 or len(matrix[0]) < 1:
            return []
        res = []
        left_row, left_col, right_row, right_col = 0, 0, len(matrix)-1, len(matrix[0])-1
        while left_row <= right_row and left_col <= right_col:
            res.extend(self.print_spiral(matrix, left_row, left_col, right_row, right_col))
            left_row += 1
            left_col += 1
            right_col -= 1
            right_row -= 1
        return res

    def print_spiral(self, matrix, left_row, left_col, right_row, right_col):
        if left_row == right_row:
            lst = [matrix[left_row][i] for i in range(left_col, right_col+1)]
            # 要return 不然后面的for循环又会重复一次
            return lst
        if left_col == right_col:
            lst = [matrix[i][left_col] for i in range(left_row, right_row+1)]
            return lst
        lst = []
        for i in range(left_col, right_col):
            lst.append(matrix[left_row][i])
        for i in range(left_row, right_row):
            lst.append(matrix[i][right_col])
        for i in range(right_col, left_col, -1):
            lst.append(matrix[right_row][i])
        for i in range(right_row, left_row, -1):
            lst.append(matrix[i][left_col])

        return lst

